package com.lyf.language.learn.atsgg.network.httpclient;

import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

/**
 * @AUTHOR LYF
 * @DATE 2022/6/8
 * @VERSION 1.0
 * @DESC
 * replace HttpURLConnection
 * use http 1.2 \ support websocket,server push msg to client
 */
public class HttpClientTests {

    @Test
    public void test1() throws IOException, InterruptedException {
        // 1.create object
        HttpClient httpClient = HttpClient.newHttpClient();
        // 2.create req
        // 2.--builder design
        // 2. req info has many and choose flexiablily , method,header,url,params
        HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("http://www.baidu.com")) //http://www.baidu.com http://localhost:8080
//                                 .GET()
                                 .header("content-type","application/json")
                                 .version(HttpClient.Version.HTTP_1_1)
                                 .build();
//        httpClient.sendAsync(httpRequest, new HttpResponse.BodyHandler<Object>() {
//            @Override
//            public HttpResponse.BodySubscriber<Object> apply(HttpResponse.ResponseInfo responseInfo) {
//                System.out.println(responseInfo.statusCode()+":");
//                return null;
//            }
//        });

        // asyn,resp chain
        CompletableFuture<HttpResponse<String>> future =
               httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
        future.thenApply(t->t.body()).thenAccept(System.out::println);

        // 3.response
        HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println(httpResponse.body());
    }




}
